const { ethers,getAddress,isAddress   } = require("ethers");

// 配置参数（替换为实际值）
const providerUrl = 'https://bsc-dataseed.binance.org/';
const privateKey = '0xa9b8e91813f80ba71b216835e28950e69bbe34a988d816e44677bffa12a0fcfd'; // 钱包私钥 D003
// const privateKey = '40f861558af28baae16eb6d56179df0af2c7651b2151c1a347ecaee638b6a394'; // 钱包私钥 D004

const routerAddress = '0x10ED43C718714eb63d5aA57B78B54704E256024E'; // PancakeSwap路由合约
const wbnbAddress = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c'; // WBNB地址
const usdtAddress = '0x55d398326f99059fF775485246999027B3197955'; // USDT地址
const appAddress = '0xDBdd51D4BC061B7eDaB60D5AD681089F51F3EC18'; // APP代币地址

async function swapBNBToToken(targetToken) {
  // 初始化提供者和钱包
  const provider = new ethers.JsonRpcProvider(providerUrl);
  const wallet = new ethers.Wallet(privateKey, provider);

  // 路由合约ABI（简化版）
  const routerAbi = [
    "function getAmountsOut(uint256 amountIn, address[] memory path) view returns (uint256[] memory amounts)",
    "function swapExactETHForTokens(uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external payable returns (uint256[] memory)"
  ];

  const router = new ethers.Contract(routerAddress, routerAbi, wallet);

  // 设置兑换参数
  const amountIn = ethers.parseEther("0.00012"); // 兑换0.1 BNB
  let path = null;
  if(targetToken=='USDT'){
    path= [wbnbAddress, usdtAddress] 
  }
  
  if(targetToken=='APP'){
    path=  [wbnbAddress, appAddress];
  }
  console.log("path:",path)

  // 获取预估兑换数量
  const amounts = await router.getAmountsOut(amountIn, path);
  if (amounts.length < 2) throw new Error("Invalid path");
  
  // 计算最小接收量（1%滑点）
  const amountOutMin = amounts[1] * 95n / 100n;
  const deadline = Math.floor(Date.now() / 1000) + 600; // 10分钟有效期

  // 执行兑换交易
  const tx = await router.swapExactETHForTokens(
    amountOutMin,
    path,
    wallet.address,
    deadline,
    { value: amountIn }
  );

  console.log(`交易已发送，哈希: ${tx.hash}`);
  const receipt = await tx.wait();
  console.log(`交易确认，区块号: ${receipt.blockNumber}`);
  console.log(`兑换成功！${ethers.formatEther(amountIn)} BNB 已兑换`);
}

// 使用示例
// swapBNBToToken('USDT').catch(console.error); // 兑换USDT
swapBNBToToken('APP').catch(console.error); // 兑换APP
  